package com.es.disped.web.controller.userrole;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.userrole.UserRoleRelService;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.RoleNode;
import com.es.disped.dao.model.UserRoleRel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value="用户角色管理")
@Controller
@RequestMapping("/manage/user/role")
public class UserRoleController extends BaseController{
	
	private static final String NAMESPACE="com.es.disped.dao.mapper.role.RoleCustomMapper";
	 
	@LogInject
	private static Logger log;

	@Autowired
	UserRoleRelService userRoleRelService; 
	
	@ApiOperation(value="用户角色绑定",httpMethod="POST",response=MsgModel.class,notes="给用户赋予角色-管理端")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody MsgModel save(@RequestBody @ApiParam(name="userRoleRel", value="用户角色关联对象",required=true) UserRoleRel userRoleRel)
	{
		int count=0;
		if(Optional.of(userRoleRel)
				.filter(uid->userRoleRel.getUserId()!=null)
				.filter(rid->userRoleRel.getRoleId()!=null)
				.isPresent())
		{
			userRoleRel.setRelId(this.getUUID());
			count=userRoleRelService.insert(userRoleRel);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-权限赋予成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-权限赋予失败", userRoleRel);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"权限赋予成功":"权限赋予失败", userRoleRel);
	}
	
	
	
	@ApiOperation(value="用户角色修改",httpMethod="POST",response=MsgModel.class,notes="修改用户角色-管理端：通过关系主键修改")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam(name="userRoleRel", value="用户角色关联对象",required=true) UserRoleRel userRoleRel)
	{
		int count=0;
		if(Optional.of(userRoleRel)
				.filter(relid->userRoleRel.getRelId()!=null)
				.isPresent())
		{
			count=userRoleRelService.updateByPrimaryKeySelective(userRoleRel);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-权限修改成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-权限修改失败", userRoleRel);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"权限修改成功":"权限修改失败", userRoleRel);
	}
	
	@ApiOperation(value="回收用户角色",httpMethod="POST",response=MsgModel.class,notes="回收用户角色-管理端：通过关联主键回收")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@RequestMapping(value="/recycle",method=RequestMethod.POST)
	public @ResponseBody MsgModel recycle(@RequestBody @ApiParam(name="userRoleRel", value="用户角色关联对象",required=true) UserRoleRel userRoleRel)
	{
		int count=0;
		String relId=userRoleRel.getRelId();
		if(!this.isNull(relId))
		{
			count=userRoleRelService.deleteByPrimaryKey(relId);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-角色收回成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-角色收回失败",relId);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"角色收回成功":"角色收回失败");
	}
	
	
	
	@ApiOperation(value="获取 checkbox 形式的 tree 结构（为用户管理提供支持）",httpMethod="POST",response=MsgModel.class,
			notes="根据用户ID和角色父类ID获取checked类型Tree列表-系统端")
//	@ApiImplicitParams({
//		@ApiImplicitParam(name="userId",value="用户ID",required=true),
//		@ApiImplicitParam(name="roleId",value="当当前检索的用户的角色节点ID，若默认为空则从根节点开始",required=false)
//	})
    @RequestMapping(value = "/roleCheckedTree", method = RequestMethod.POST)
    public @ResponseBody List<RoleNode> getRoleCheckedTree(@RequestBody @ApiParam(name="paramMap",value="当前检索的用户的角色节点ID，若默认为空则从根节点开始",required=false) Map<String, Object> paramMap) {

        if (!paramMap.containsKey("roleId")) {
			paramMap.put("roleId", "00000000000000000000000000000000");
        }

        List<RoleNode> nodeList = new ArrayList<>();
        List<RoleNode> rootList = this.getService().selectList(NAMESPACE+".getRoleCheckedNode", paramMap);
        for (RoleNode roleNode : rootList) {
            roleNode.setChildren(getRoleCheckedNode(paramMap.get("userId").toString(), roleNode.getId()));
            nodeList.add(roleNode);
        }
        return nodeList;
    }
	
	
    
    /**
     * 角色 checkbox 形式 tree 加载（为用户管理提供支持）<br>
     *
     * @param userId 用户Id
     * @param pid    父Id
     * @return List<RoleNode> 角色节点列表集合
     */
	private List<RoleNode> getRoleCheckedNode(String userId, String pid) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId);
        paramMap.put("roleId", pid);
        List<RoleNode> roleList = this.getService().selectList(NAMESPACE+".getRoleCheckedNode", paramMap);
        return roleList;
	}
}
